#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <memory>
#include <filesystem> // C++ 17 后的标准
#include <unistd.h>
#include <time.h>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace LockModule;
    // 获取当前时间
    std::string CurrTime()
    {
        // 获取当前时间戳
        time_t time_stamp = time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp, &curr);
        char buffer[32];
        snprintf(buffer, sizeof(buffer), "%d%d%d %d-%d-%d", curr.tm_year + 1900, curr.tm_mon + 1, curr.tm_mday,
                 curr.tm_hour, curr.tm_min, curr.tm_sec);
        return buffer;
    }
    // 日志路径和文件名
    const std::string DefaultLoggpath = "./Log/";
    const std::string DefaultLoggname = "Log.txt";
    // 1.日志等级
    enum class Loglevel
    {
        DEBUG = 1,
        INFO,
        WARING,
        ERROR,
        FATAL
    };
    // 将日志等级转化为字符串输出
    std::string Level2String(Loglevel level)
    {
        switch (level)
        {
        case Loglevel::DEBUG:
            return "DEBUG";
        case Loglevel::INFO:
            return "INFO";
        case Loglevel::WARING:
            return "WARING";
        case Loglevel::ERROR:
            return "ERROR";
        case Loglevel::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }
    // 2.刷新策略,只进行刷新,不提供方法
    class LogStrategy
    {
    public:
        // 基类析构需要设置为虚类
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };
    // 2.1控制台刷新策略
    class ConsoleStrategy : public LogStrategy
    {
    public:
        ConsoleStrategy()
        {
        }
        ~ConsoleStrategy()
        {
        }
        void SyncLog(const std::string &message)
        {
            LockGard lock(_mutex);
            std::cout << message << std::endl;
        }

    private:
        Mutex _mutex;
    };
    // 2.2文件级(磁盘)策略
    class FileStrategy : public LogStrategy
    {
    public:
        FileStrategy(const std::string gpath = DefaultLoggpath, const std::string gname = DefaultLoggname)
            : _logpath(gpath), _logname(gname)
        {
            LockGard lock(_mutex);
            // 检测文件是否存在
            if (std::filesystem::exists(_logpath))
            {
                return;
            }
            // 不存在就新建文件
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << std::endl;
            }
        }
        ~FileStrategy()
        {
        }
        void SyncLog(const std::string &message)
        {
            // C++对文件处理操作
            LockGard lock(_mutex);
            std::string Log = _logpath + _logname; //"/Log/Log.txt"
            std::ofstream out(Log, std::ios::app); // 日志写入一定是追加写入
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }

    private:
        Mutex _mutex;
        std::string _logpath;
        std::string _logname;
    };
    // 3.日志类,构建日志字符串,根据策略进行刷新
    class Logger
    {
    public:
        Logger()
        {
            // 默认采用控制台输出策略
            _strategy = std::make_shared<ConsoleStrategy>();
        }
        void EnableConsoleStrategy()
        {
            _strategy = std::make_shared<ConsoleStrategy>();
        }
        void EnableFileStrategy()
        {
            _strategy = std::make_shared<FileStrategy>();
        }
        ~Logger()
        {
        }
        // 一个Logmessage类就是一个完整的日志信息
        // 析构的时候刷新
        class Logmessage
        {
        public:
            Logmessage(Loglevel level, const std::string &filename, int line, Logger &logger)
                : _currtime(CurrTime()),
                  _level(level),
                  _pid(getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer
                    << "[" << _currtime << "]"
                    << " [" << Level2String(_level) << "]"
                    << " [" << _pid << "]"
                    << " [" << _filename << "]"
                    << " [" << _line << "]";
                _loginfo = ssbuffer.str();
                // 日志前半部分完成
            }
            template <typename T>
            Logmessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }
            ~Logmessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }

        private:
            // 一条完整的信息: [2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16]
            //+ 日志的可变部分(<< "hello world" << 3.14 << a << b;)
            std::string _currtime; // 当前时间
            Loglevel _level;       // 当前日志等级
            pid_t _pid;            // 进程怕pid
            std::string _filename; // 源文件
            int _line;             // 所在行数
            Logger &_logger;       // 根据不同的策略进行刷新
            std::string _loginfo;  // 一条完整的日志信息
        };
        Logmessage operator()(Loglevel level, const std::string &filename, int line)
        {
            return Logmessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy; // 日志刷新的策略方案
        // 智能指针
    };
    Logger logger;
#define LOG(Level) logger(Level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableConsoleStrategy()
#define ENABLE_FILE_LOG() logger.EnableFileStrategy()
}